define(['./module'],function(advertisemodule){
	'use strict';

	advertisemodule.controller('advertisecontent',serveradvertisecontentctrl);
	function serveradvertisecontentctrl($stateParams,$http,$location,$compile,$scope,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer,GoodsTypeService){
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="gt.selectAll" ng-click="gt.toggleAll(gt.selectAll,gt.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
				type:'POST',
				url:'../mall/products/findProductByPage',
				dataSrc:'data'
			})
			.withOption('processing',true)
			.withOption('paging',true)
			.withOption('serverSide',true)
			.withOption('createdRow',function(row,data,dataIndex){
				$compile(angular.element(row).contents())($scope);
			})
			.withOption('headerCallback', function(header) {
				if (!$scope.headerCompiled) {
					$scope.headerCompiled = true;
					$compile(angular.element(header).contents())($scope);
				}
			})
			.withOption('stateSave', true)
			.withOption('rowCallback',rowCallback)
			.withPaginationType('full_numbers')
			.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){

		});
		vm.dtColumns=[
			DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
				vm.selected[full.id]=false;
				return "<input type='checkbox' ng-model=\"gt.selected['"+data.id+"']\" ng-click=\"gt.toggleOne(gt.selected)\">";
			}),
			DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
			DTColumnBuilder.newColumn(null).withTitle('图片').notSortable().renderWith(imgHtml),
			DTColumnBuilder.newColumn('psn').withTitle('货号').notSortable(),
			DTColumnBuilder.newColumn('productname').withTitle('货物名称').notSortable(),
			DTColumnBuilder.newColumn('nname').withTitle('分类').notSortable(),
			DTColumnBuilder.newColumn('goodstypename').withTitle('商品类型').notSortable(),
			DTColumnBuilder.newColumn('stock').withTitle('库存').notSortable(),
			DTColumnBuilder.newColumn('saleprice').withTitle('销售价').notSortable(),
			DTColumnBuilder.newColumn('memberprice').withTitle('会员价').notSortable(),
			DTColumnBuilder.newColumn('cost').withTitle('成本价').notSortable(),
			DTColumnBuilder.newColumn('salestatus').withTitle('销售状态').notSortable(),
			DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable()];
		function imgHtml(data,type,full,meta){
			return '<img style="width:50px;height:50px;" ng-src="'+data.mainimg+'" alt="Photo" />';
		}

		function reloadData(){
			var resetPaging = false;
			vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}


		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:'',
				psn:'',
				goodstypeid:''
			};
			if($scope.productname!=undefined){
				searchParams.name=$scope.productname;

			}
			if($scope.psn!=undefined){
				searchParams.psn=$scope.psn;
			}
			if($scope.selectedgoodstype.goodstypeid!=undefined){
				searchParams.goodstypeid=$scope.selectedgoodstype.goodstypeid;
			}else{
				$scope.errors = {
					show: true,
					msg: '请选择商品类型'
				}
				return false;
			}
			vm.dtOptions['ajax'].data=searchParams;
			vm.dtInstance.reloadData(callback, resetPaging);
		}
		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;

		}

		function someClickHandler(info) {
			vm.message = info.id + ' - ' + info.name;
			console.log("======"+info);
			$scope.selectedproducts = info;
		}
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
			$('td', nRow).bind('click', function() {
				$scope.$apply(function() {
					vm.someClickHandler(aData);
				});
			});
			return nRow;
		}



		/**
		 * 删除选择的货物
		 * @param index
		 */
		$scope.removeselectproduct=function(){
			$scope.selectedproducts=undefined;
		}

		//查询所有商品类型
		$scope.findallgoodstype = function () {
			var promise = GoodsTypeService.query();
			promise.then(function (data) {
				$scope.goodstypeselect = data.beanlist;
			}, function (data) {
				$scope.errors = {
					show: true,
					msg: '系统异常'
				}
			});
		};

		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate||$stateParams.operate;
		if(operate!=undefined&&operate=="save"){
			//获取所有的广告信息
			$scope.findalladvs = function () {
				$http({
					method:'POST',
					url:'../mall/advertise/findAll'
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.advselect=data.beanlist;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			};

			$scope.advtypechange=function(){
				if($scope.type=="1"){
					$scope.gspshow=false;
					$scope.productshow=true;
				}else{
					$scope.gspshow=true;
					$scope.productshow=false;
				}
			};



			//获取所有专题商品
			$scope.findallgoodsspecial = function () {
				$http({
					method:'POST',
					url:'../mall/goodsspecial/findAll'
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.gspselect=data.beanlist;
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
						show:true,
						msg:'系统异常'
					}
				});
			};

			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='绑定广告系统内容';
			$scope.status="1";
			$scope.type="2";
			$scope.gspshow=true;

			
			
			//保存数据方法
			$scope.save=function(){
				if($scope.selectedadv==undefined){
					$scope.errors={
							show:true,
							msg:'请选择广告'
					}
					return false;
				}
				//关联的信息ID
				var rpid="";
				//选择的是关联专题
				if($scope.type=="2"){
					if($scope.selectedgsp==undefined){
						$scope.errors={
							show:true,
							msg:'请选择需要关联的专题'
						}
						return false;
					}else{
						rpid=$scope.selectedgsp.id;
					}
				}
				if($scope.type=="1"){
					if($scope.selectedproducts==undefined){
						$scope.errors={
							show:true,
							msg:'请选择需要关联的货物'
						}
						return false;
					}else{
						rpid=$scope.selectedproducts.id;
					}
				}

				$http({
					method:'POST',
					url:'../mall/advertisecontent/save',
					data:{
						'advertiseid':$scope.selectedadv.id,
						'rpid':rpid,
						'type':$scope.type,
						'status':$scope.status
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'绑定广告内容成功'
						}
						$location.path("/advertisecontentment");
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		
		}

	}

	advertisemodule.controller('advertisecontentment',ServerAdvertiseListCtrl);
	//查询列表数据
	function ServerAdvertiseListCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/advertisecontent/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')
		
		$scope.$on('handleRequest',function(){
			
		});
		
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return '<input type="checkbox" ng-model="showCase.selected['+data.id+']" ng-click="showCase.toggleOne(showCase.selected)">';
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		              DTColumnBuilder.newColumn('rptitle').withTitle('标题').notSortable(),
		              DTColumnBuilder.newColumn(null).withTitle('广告图').notSortable().renderWith(imgHtml),
			          DTColumnBuilder.newColumn('type').withTitle('关联类型').notSortable(),
			          DTColumnBuilder.newColumn('rpid').withTitle('关联内容id').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable()];
		function imgHtml(data,type,full,meta){
			return '<img style="width:50px;height:50px;" ng-src="'+data.smainimg+'" alt="Photo" />';
		}

		
		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}



		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.name!=undefined){
				searchParams.name=$scope.name;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}

		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}

		
		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/advertisecontent').search({'operate':'save'});
		}
		
		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/advertisecontent/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.info={
								show:true,
								msg:'批量删除成功'
						}
						reloadData();
					}
					
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}
	}
	/*=====End Of Find List MemberT=====*/
});